package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/14  0:01
 * @description：TODO
 */
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public void testLock() {
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        //获取值
        Integer num = (Integer) redisTemplate.opsForValue().get("num");
        //值++
        num++;
        //设置值
        redisTemplate.opsForValue().set("num",num);
        lock.unlock();
    }
    /* @Override
    public void testLock() {
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", 0);
        if(lock){
            //获取到了锁
            //获取值
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            //值++
            num++;
            //设置值
            redisTemplate.opsForValue().set("num",num);
            redisTemplate.delete("lock");
        } else{
            //未获得锁
            testLock();
        }
    }*/
}
